<?php
namespace App\Services;

use App\Models\CheckModel;
use App\Models\OverflowBreakageDetailModel;
use App\Models\OverflowBreakageModel;
use App\Models\SalesReturnGoodsDetailModel;
use App\Models\SalesReturnInStorageModel;
use App\Models\SalesReturnModel;
use App\Services\StorageManageService;
use Illuminate\Support\Facades\DB;
use App\Models\SellGoodsDetail;
use App\Models\SellModel;
use App\Models\SellOutStorageModel;

/**
 * 出入库及撤销
 * Class OutInRepealService
 * @package App\Services
 */
class OutInRepealService
{
    /**
     * 出入库
     * change 在 2021/11/10 16:13 创建
     * @param $type 1-销售 2-退款
     * @param $id   主键id
     * @param $status 入库状态：1-部分 2-全部
     * @param $goods  商品信息 obj
     */
    static public function outIn($type,$id,$status,$goods='',$data){
        //开启事务
        DB::beginTransaction();
        try{
            $paramsArr = [];//出入库参数
            $paramsArr['all_id'] = $id;
            isset($data['remark'])?$paramsArr['remark'] = $data['remark']:$paramsArr['remark'] = '';
            $paramsArr['all_id_type'] = 2;//销售退货均为2
            if ($type==1){//销售
                $paramsArr['out_storage_time'] = $data['in_storage_time'];
                if($status==1){//部分出库
                    SellModel::where('id',$id)->update(['out_status'=>1]);//更新销售入库状态
                    //部分出库临时存储
                    $goods = json_decode($goods,true);
                    foreach ($goods as $key=>$value){
                        $sellOutStorageModel = SellOutStorageModel::where(['name'=>$value['name'],'type_name'=>$value['type_name'],'sell_id'=>$id])->first();
                        $num = SellGoodsDetail::where(['name'=>$value['name'],'type_name'=>$value['type_name'],'sell_id'=>$id])->value('num');//原生入库数量
                        if($sellOutStorageModel){//更新数量

                            if(($sellOutStorageModel->num+$value['num'])>$num){
                                return 1;
                            }
                            $sellOutStorageModel->num = $sellOutStorageModel->num+$value['num'];
                            $sellOutStorageModel->save();
                        }else{
                            //添加
                            if($value['num']>$num){
                                return 1;
                            }
                            $datavalue['sell_id'] = $id;
                            $datavalue['name'] = $value['name'];
                            $datavalue['type_name'] = $value['type_name'];
                            $datavalue['num'] = $value['num'];
                            $datavalue['price'] = $value['price'];
                            $datavalue['warehouse'] = $value['warehouse'];
                            $datavalue['warehouse_id'] = $value['warehouse_id'];
                            $datavalue['materiel_type_id'] = $value['materiel_type_id'];
                            SellOutStorageModel::insert($datavalue);
                        }
                        //更新商品入库数量
                        $sellGoods = SellGoodsDetail::where(['name'=>$value['name'],'type_name'=>$value['type_name'],'sell_id'=>$id])->first();
                        $sellGoods->out_num = $sellGoods->out_num+$value['num'];
                        $sellGoods->is_out = 1;
                        $sellGoods->save();
                        $paramsArr['content'][$key]['name'] = $value['name'];
                        $paramsArr['content'][$key]['price'] = $value['price'];
                        $paramsArr['content'][$key]['type_name'] = $value['type_name'];
                        $paramsArr['content'][$key]['num'] = $value['num'];
                        $paramsArr['content'][$key]['warehouse'] = $value['warehouse'];
                        $paramsArr['content'][$key]['warehouse_id'] = $value['warehouse_id'];
                    }
                    //调用出库
                    $res = StorageManageService::outStorage($data['user_id'], $data['main_id'], $paramsArr, $id);
                    if($res['code']){
                        return $res;
                    }

                    //入库检测
                    $sellGoodsDetail = SellGoodsDetail::where('sell_id',$id)->get();
                    $flag = 1;
                    foreach ($sellGoodsDetail as $val){
                        if($val['num']!=$val['out_num']){
                            $flag = 0;
                        }
                    }
                    if($flag){
                        SellModel::where('id',$id)->update(['out_status'=>2]);//全部完成更新状态
                        //出库完成更新商品出库状态
                        SellGoodsDetail::where('sell_id',$id)->update(['out_status'=>1]);
                        //添加成本
                        foreach ($res['data']  as $item){
                            SellGoodsDetail::where(['name'=>$item['materiel_name'],'type_name'=>$item['type_name'],'sell_id'=>$id])->update(['cost_price'=>$item['cost_price']]);
                        }
                        //更新审核列表状态
                        CheckModel::where(['main_id'=>$data['main_id'],'type'=>2,'all_id'=>$id])->update(['status'=>1,'out_in_status'=>0]);
                        return 3;
                    }else{
                        CheckModel::where(['main_id'=>$data['main_id'],'type'=>2,'all_id'=>$id])->update(['out_in_status'=>1]);
                    }


                }elseif ($status==2){//全部
                    //防重复
                    $outStatus = SellModel::where('id',$id)->value('out_status');
                    if($outStatus==2){
                        return ['code'=>1,'msg'=>'请勿重复出库'];
                    }
                    SellModel::where('id',$id)->update(['out_status'=>2]);//更新销售入库状态
//                    //出库完成更新商品出库状态
//                    SellGoodsDetail::where('sell_id',$id)->update(['out_status'=>1]);
                    //更新单商品出库状态
                    $salesReturnGoodsDetailModel = SellGoodsDetail::where('sell_id',$id)->get();

                    foreach ($salesReturnGoodsDetailModel as $k=>$val){
                        $val->out_num = $val['num'];
                        $val->is_out = 1;
                        $val->out_status = 1;
                        $val->save();
                        $paramsArr['content'][$k]['name'] = $val['name'];
                        $paramsArr['content'][$k]['price'] = $val['price'];
                        $paramsArr['content'][$k]['type_name'] = $val['type_name'];
                        $paramsArr['content'][$k]['num'] = $val['num'];
                        $paramsArr['content'][$k]['warehouse'] = $val['warehouse'];
                        $paramsArr['content'][$k]['warehouse_id'] = $val['warehouse_id'];
                    }

                    //调用出库
                    $res = StorageManageService::outStorage($data['user_id'], $data['main_id'], $paramsArr, $id);
                    if($res['code']){
                        return $res;
                    }

                    //添加成本
                    foreach ($res['data']  as $item){
                        SellGoodsDetail::where(['name'=>$item['materiel_name'],'type_name'=>$item['type_name'],'sell_id'=>$id])->update(['cost_price'=>$item['cost_price']]);
                    }
                    //更新审核列表状态
                    CheckModel::where(['main_id'=>$data['main_id'],'type'=>2,'all_id'=>$id])->update(['status'=>1]);
                }
            }elseif ($type==2){//退款
                $paramsArr['in_storage_time'] = $data['in_storage_time'];
                if($status==1){//部分入库
                    SalesReturnModel::where('id',$id)->update(['out_status'=>1]);//更新销售入库状态
                    //部分入库临时存储
                    $goods = json_decode($goods,true);
                    foreach ($goods as $k=>$value){
                        $salesReturnInStorageModel = SalesReturnInStorageModel::where(['name'=>$value['name'],'type_name'=>$value['type_name'],'return_id'=>$id])->first();
                        $num = SalesReturnGoodsDetailModel::where(['name'=>$value['name'],'type_name'=>$value['type_name'],'return_id'=>$id])->value('num');//原始入库数量
                        if($salesReturnInStorageModel){//更新数量
                            if(($salesReturnInStorageModel->num+$value['num'])>$num){
                                return 1;
                            }
                            $salesReturnInStorageModel->num = $salesReturnInStorageModel->num+$value['num'];
                            $salesReturnInStorageModel->save();
                        }else{
                            //添加
                            if($value['num']>$num){
                                return 1;
                            }
                            $datavalue['return_id'] = $id;
                            $datavalue['name'] = $value['name'];
                            $datavalue['type_name'] = $value['type_name'];
                            $datavalue['num'] = $value['num'];
                            $datavalue['price'] = $value['price'];
                            $datavalue['warehouse'] = $value['warehouse'];
                            $datavalue['warehouse_id'] = $value['warehouse_id'];
                            $datavalue['materiel_type_id'] = $value['materiel_type_id'];
                            SalesReturnInStorageModel::insert($datavalue);
                        }
                        //更新商品入库数量
                        $srGoods = SalesReturnGoodsDetailModel::where(['name'=>$value['name'],'type_name'=>$value['type_name'],'return_id'=>$id])->first();
                        $srGoods->in_num = $srGoods->in_num+$value['num'];
                        $srGoods->is_in = 1;
                        $srGoods->save();
                        $paramsArr['content'][$k]['name'] = $value['name'];
                        $paramsArr['content'][$k]['type_name'] = $value['type_name'];
                        $paramsArr['content'][$k]['num'] = $value['num'];
                        $paramsArr['content'][$k]['warehouse'] = $value['warehouse'];
                        $paramsArr['content'][$k]['warehouse_id'] = $value['warehouse_id'];
                    }
                    //调用入库
                    $res = StorageManageService::inStorage($data['user_id'], $data['main_id'], $paramsArr);
                    if($res['code']){
                        return $res;
                    }
                    //入库检测
                    $salesReturnGoodsDetailModel = SalesReturnGoodsDetailModel::where('return_id',$id)->get();
                    $flag = 1;
                    foreach ($salesReturnGoodsDetailModel as $val){
                        if($val['num']!=$val['in_num']){
                            $flag = 0;
                        }
                    }
                    if($flag){
                        SalesReturnModel::where('id',$id)->update(['out_status'=>2]);//全部完成更新状态
                        return 3;
                    }


                }elseif ($status==2){//全部
                    //防重复
                    $outStatus = SalesReturnModel::where('id',$id)->value('out_status');
                    if($outStatus==2){
                        return ['code'=>1,'msg'=>'请勿重复入库'];
                    }
                    SalesReturnModel::where('id',$id)->update(['out_status'=>2]);//更新销售入库状态
                    //更新单商品入库状态
                    $salesReturnGoodsDetailModel = SalesReturnGoodsDetailModel::where('return_id',$id)->get();
                    foreach ($salesReturnGoodsDetailModel as $k=>$val){
                        $val->in_num = $val['num'];
                        $val->is_in = 1;
                        $val->save();
                        $paramsArr['content'][$k]['name'] = $val['name'];
                        $paramsArr['content'][$k]['type_name'] = $val['type_name'];
                        $paramsArr['content'][$k]['num'] = $val['num'];
                        $paramsArr['content'][$k]['warehouse'] = $val['warehouse'];
                        $paramsArr['content'][$k]['warehouse_id'] = $val['warehouse_id'];
                    }
                    //调用入库
                    $res = StorageManageService::inStorage($data['user_id'], $data['main_id'], $paramsArr);
                    if($res['code']){
                        return $res;
                    }
                }

            }
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return 2;
        }
    }

    /**
     * 撤销
     * change 在 2021/11/11 14:32 创建
     * @param $id    主键
     * @param $type  1-销售 2-退货  3-报溢报损
     */
    static public function repeal($id,$type){

        if($type==1){//销售
            $sellModel = SellModel::find($id);
            if($sellModel['out_status']==1 || $sellModel['out_status']==2){//全部或部分
                $res = StorageManageService::cancelOut(2, $id);
                if($res!=1){
                    return $res;
                }
            }

            SellGoodsDetail::where(['main_id'=>$sellModel['main_id'],'sell_id'=>$id])->update(['repeal_status'=>1]);//销售商品撤销
            CheckModel::where(['main_id'=>$sellModel['main_id'],'all_id'=>$id,'type'=>2])->update(['repeal_status'=>1]);//更新销售审批状态
            $sellModel->repeal_status = 1;
            return $sellModel->save();

        }elseif($type==2){//退货
            $salesReturnModel = SalesReturnModel::find($id);
            if($salesReturnModel['out_status']==1 || $salesReturnModel['out_status']==2){//部分
                //出库参数
                $res = StorageManageService::cancelIn(2, $id);
                if($res!=1){
                    return $res;
                }
            }
            $salesReturnModel->repeal_status = 1;
            return $salesReturnModel->save();

        }elseif($type==3){//报溢报损

            $overflowBreakageModel = OverflowBreakageModel::find($id);
            //入库检查(未入库直接改状态)
            if($overflowBreakageModel['status']==0 || $overflowBreakageModel['status']==2){
                //更新审批状态
                if($overflowBreakageModel['type']==0) {//报溢
                    CheckModel::where(['main_id'=>$overflowBreakageModel['main_id'],'all_id'=>$id,'type'=>0])->update(['repeal_status'=>1]);//更新报溢审批状态
                }else{
                    CheckModel::where(['main_id'=>$overflowBreakageModel['main_id'],'all_id'=>$id,'type'=>1])->update(['repeal_status'=>1]);//更新报损审批状态
                }
                $overflowBreakageModel->repeal_status = 1;
                return $overflowBreakageModel->save();
            }

            if($overflowBreakageModel['type']==0){//报溢
                //入库调用
                $res = StorageManageService::cancelIn(1, $id);
                if($res!=1){
                    return $res;
                }
                CheckModel::where(['main_id'=>$overflowBreakageModel['main_id'],'all_id'=>$id,'type'=>0])->update(['repeal_status'=>1]);//更新报溢审批状态

            }elseif($overflowBreakageModel['type']==1){//报损
                //出库调用
                $res = StorageManageService::cancelOut(1, $id);
                if($res!=1){
                    return $res;
                }
                CheckModel::where(['main_id'=>$overflowBreakageModel['main_id'],'all_id'=>$id,'type'=>1])->update(['repeal_status'=>1]);//更新报损审批状态
            }
            $overflowBreakageModel->repeal_status = 1;
            return $overflowBreakageModel->save();
        }
    }
}
